import dTalkApi from '../core/dTalkApi';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import storeRecoderModel from '../model/storeRecoderModel';
import consumerRecoderModel from '../model/consumerRecoderModel';
import * as moment from 'moment';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import storeInfoModel from '../model/storeInfoModel';
import formDataService from './formDataService';

class VisitMonthPlanService {
    constructor() { }

    //显示员工今日计划的内容 
    async listMonthPlanByNowday(userid: string, date1: string) {
        // let date1 = moment().format('YYYY-MM-DD');
        let nowdayplanList = await visitMonthPlanModel.find({ userId: userid, planDate: date1,"$or":[{comment:1,planStatus:{$ne:'同意'}},{comment:2,planStatus:'申请取消',cancelApply:'否'},{comment:2,planStatus:{$ne:'同意'},cancelApply:'是'},{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}] });
        let json: any = {};
        let json2: any = [];//今日计划的body部分
        if (nowdayplanList.length>0) {
            for (let index = 0; index < nowdayplanList.length; index++) {
                let element = nowdayplanList[index];//element=visitMonthPlan
                let recoderDetail: any = '';
                if (element.visitRecoder == '' || element.visitRecoder == null) {
                    recoderDetail = '';
                } else {
                    if (element.plantype == '门店') {
                        recoderDetail = await storeRecoderModel.findById({ _id: element.visitRecoder });
                    } else {
                        recoderDetail = await consumerRecoderModel.findById({ _id: element.visitRecoder });
                    }
                }
                json2.push({
                    id: element._id,   //id
                    visitRecoder: recoderDetail,//拜访记录
                    planDate: element.planDate,//拜访日期
                    consumerName: element.consumerName,//客户名称
                    consumerCode: element.consumerCode,//客户编码
                    customerType: element.customerType,//客户类型
                    plantype: element.plantype,//拜访类型
                    planStatus: element.planStatus, //状态
                    purpose: element.purpose,//拜访目的
                    userId: element.userId, //员工id
                    comment: element.comment, //说明-----用于说明该条数据是导入的计划数据|还是员工申请的临时计划数据
                    cancelApply: element.cancelApply,//是否申请取消
                    remark: element.remark  //审批意见
                });  
            }
        }
        let reachStoreRate_one_employee =await formDataService.getReachStoreRate_one_employeeDate1ToDate2(userid,date1,date1)
        let reachStoreRate = (reachStoreRate_one_employee*100).toFixed(2);
        //今日计划的总条数
        let planTotalCount = await visitMonthPlanModel.count({ userId: userid, planDate: date1, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' },{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}] });
        //统计一个员工一天已经拜访的门店有多少家
        let countVisitedStore = await storeRecoderModel.count({ userid: userid, date: date1, planType: '门店' });
        //统计一个员工一天的达成客户与门店多少家
        let countReachConsumer = await consumerRecoderModel.count({ userid: userid, planDate: date1 });
        let countReachStore = await storeRecoderModel.count({ userid: userid, planDate: date1 });
        let reacheTotalCount = countReachConsumer + countReachStore;
        let consumerreach_Rate = 0;
        if (planTotalCount == 0) {
            consumerreach_Rate = 0
        } else {
            consumerreach_Rate = (reacheTotalCount / planTotalCount) * 100;
        }
        let consumerRate = consumerreach_Rate.toFixed(2);
        // let userInfo = await dTalkApi.getUserDetail(userid);
        let pl=await visitMonthPlanModel.findOne({userId:userid,"$and":[{user:{$ne:null}},{user:{$ne:''}}]})
        let name:any='';
        if(pl&&pl.user){
            name=pl.user;
        }else{
            let access_token=await dTalkApiUtil.getAccessToken();
            let userInfo=await dTalkApi.getUserDetail(userid,access_token);
            if(userInfo&&userInfo.name){
                name=userInfo.name;
            }
        }
        json = {
            header: {
                one: '计划' + planTotalCount + '家,|达成' + reacheTotalCount + '家',
                two: '客户拜访达成率' + consumerRate + '%',
                three: '已拜访门店' + countVisitedStore,
                four: '门店达标率' + reachStoreRate + '%'
            },
            userid: userid,//员工id
            //name: pl.user,//员工姓名
            name:name,//员工姓名
            // name: userInfo.name,//员工姓名
            plandate: date1,
            body: json2  //拜访的客户的列表
        }
        return json;
    }
   
    //员工申请的临时计划并保存临时计划  数量只是一个   
    async saveTemporaryPlan(res: any, user: any) {
        let month = moment(res.planDate).format('MM');
        let year = moment(res.planDate).format('YYYY');
        let con_address:any='';//客户或者门店的地址
        if(res.plantype=='现有客户'){
            let con_info=await consumerRecoderModel.findOne({comment:1,consumerCode:res.consumerCode});
            if(con_info&&con_info.consumerAddress){
                con_address=con_info.consumerAddress;
            }
        }else if(res.plantype=='门店'){
            let sto_info=await storeInfoModel.findOne({storeCode:res.consumerCode});
            if(sto_info&&sto_info.store_address){
                con_address=sto_info.store_address;
            }
        }
        //获取员工信息详情
        let re_ = await visitMonthPlanModel.create({
            sourceId: res.userId + '&' + res.planDate,
            leadIndate: '',
            //员工信息
            user: user.name,
            userId: res.userId,
            jobnumber: user.jobnumber,
            deptId: user.department,
            avatar: user.avatar,
            provinceManager: "",
            province: "",
            areaManager: "",
            roles: "",          //角色
            modelManager: "",      //模块负责人
            manageModel: "",     //模块
            nationalManager: "",//全国负责人
            area: "",
            city: "",
            team: '',//员工所在团队
            nation: '',//全国
            provinceName: '',//省份名称
            areaName: '',//区域名称
            manageModelName: '',//模块名称
            teamName: '',//团队名称
            nationName: '',//全国名称
            channel: res.channel,
            consumerName: res.consumerName,
            consumerCode: res.consumerCode,
            customerType: res.customerType,
            //新增开始
            consumerAddress:con_address,
            isAdjust:false,
            year:year,
            //新增结束
            planDate: res.planDate,
            //计划的信息
            rest: '',
            meeting: '',
            month: month,
            plantype: res.plantype,
            planStatus: '待审核',
            comment: 2,
            purpose: res.purpose,
            mark: '',
            cancelApply: '',
            visitRecoder: '',
            remark: ''
        });
        // console.log(re_,'re_re_re_re_re_re_re_');
        return re_;
       
    }

    //显示员工某个日期的计划内容 即显示员工的计划(包括导入的计划与申请的临时计划)
    async listplanByDate(userid: string, date1: string) {
        // console.log('userid是:' + userid + '-----日期是:' + date1);
        let date = moment(date1).format('YYYY-MM-DD')
        let date_planList = await visitMonthPlanModel.find({ userId: userid, planDate: date });
        let json: any = {};
        let json2: any = [];
        if (date_planList.length) {
            for (let index = 0; index < date_planList.length; index++) {
                let element = date_planList[index];
                json2.push({
                    id: element._id,   //id
                    visitRecoder: element.visitRecoder,//拜访记录
                    planDate: element.planDate,//拜访日期
                    consumerName: element.consumerName,//客户名称
                    consumerCode: element.consumerCode,//客户编码
                    plantype: element.plantype,//拜访类型
                    planStatus: element.planStatus, //状态
                    customerType: element.customerType,//客户类型
                    purpose: element.purpose,//拜访目的
                    userId: element.userId, //员工id
                    comment: element.comment, //说明-----用于说明该条数据是导入的计划数据|还是员工申请的临时计划数据
                    cancelApply: element.cancelApply,//是否申请取消
                    remark: element.remark  //审批意见
                })
            }
        }
        json = {
            userid: userid,//员工id
            date: date,  //日期
            data: json2  //数据
        }
        return json;

    }

    //申请取消的计划只有临时计划
    async listplanByDate2(userid: string, date1: string) {
        // console.log('userid是:' + userid + '-----日期是:' + date1);
        let date = moment(date1).format('YYYY-MM-DD')
        let date_planList = await visitMonthPlanModel.find({ userId: userid, planDate: date,comment:2 });
        let json: any = {};
        let json2: any = [];
        if (date_planList.length) {
            for (let index = 0; index < date_planList.length; index++) {
                let element = date_planList[index];//element=visitMonthPlanModel
                json2.push({
                    id: element._id,   //id
                    visitRecoder: element.visitRecoder,//拜访记录
                    planDate: element.planDate,//拜访日期
                    consumerName: element.consumerName,//客户名称
                    consumerCode: element.consumerCode,//客户编码
                    plantype: element.plantype,//拜访类型
                    planStatus: element.planStatus, //状态
                    customerType: element.customerType,//客户类型
                    purpose: element.purpose,//拜访目的
                    userId: element.userId, //员工id
                    comment: element.comment, //说明-----用于说明该条数据是导入的计划数据|还是员工申请的临时计划数据
                    cancelApply: element.cancelApply,//是否申请取消
                    remark: element.remark  //审批意见
                })
            }
        }
        json = {
            userid: userid,//员工id
            date: date,  //日期
            data: json2  //数据
        }
        return json;

    }

    //批量更新planStatus  可以多个也可以一个 _id
    //该方法是用于更新planStatus的状态(员工申请取消或待审核的临时计划审批通过后,由于各种原因拜访不了)
    async updatePlanStatus(idList: any) {
        for (let index = 0; index < idList.length; index++) {
            let element = idList[index];
            let b=  await visitMonthPlanModel.update({ _id: element }, { planStatus: '待审核', cancelApply: '是' }, { upsert: true });
            console.log(element,'??????????',b,'b_b_b_b_b_b_b_b_')
        }
    }

    //批量调整拜访日期
    async updatePlanStatus2(idList: any) {
        if(idList.length>0){
            for (let index = 0; index < idList.length; index++) {
                let element = idList[index];
                //element={id:_id,date:''}
                await visitMonthPlanModel.update({ _id: element.id }, { planDate:element.date,planStatus: '待审核', cancelApply: '是' }, { upsert: true });
            }
        }
        
    }

    //定时判断员工的拜访计划的拜访日期,拜访日期是今天,明天0点没写拜访记录的更新planStatus状态-----未写拜访记录
    async updatePlanStatus3(date: string, userid: string, code: string, name: string, type: string) {
        let date1 = moment(date).format('YYYY-MM-DD');
        let list = await visitMonthPlanModel.findOne({ planDate: date1, userId: userid, consumerCode: code, consumerName: name, plantype: type });
        if (!list||(list&&(list.visitRecoder == '' || list.visitRecoder == null))) {
            let a = await visitMonthPlanModel.update({ planDate: date1, userId: userid, consumerCode: code, consumerName: name, plantype: type }, { planStatus: '未写拜访记录' });
            // console.log(a,'aaaaaaaaaaaaaaaa');
        }
        console.log('更新planStatus状态结束!!!!!!');
    }

    //根据_id查询visitMonthPlanModel
    async getVisitMonthPlanDataById(id: string) {
        let data = await visitMonthPlanModel.findById({ _id: id });
        // console.log(data,'<-----------------')
        let patt1 = new RegExp(/\s+/g);  
        if(data&&data.customerType){
            let str:any=data.customerType
            if (patt1.test(str)) {  
                console.log("有空格");  
                let d=str.replace(new RegExp(' ',"gm"), '')
                data.customerType=d;
            } 
        }
        return data;
    }

    async getUserIdByCode(code: string, cache: any,access_token:string) {
        if (cache[code]) {
            return cache[code]
        } else {
            let result = await dTalkApi.getDingDingAdressList(code,access_token);
            // console.log(result.total);
            if (!result.list || result.list.length == 0) {
                console.log("工号", code, "未找到");
                return null;
            }
            cache[code] = result.list[0];
            return cache[code]
        }
    }

    async getUserOriginizationById(id:string,cache:any,access_token:string){
       let idList:any=[];
        if(cache[id]){
            return [];
        }else{
            let groupName:any=[];
            let province: any = '';
            let area: any = '';
            let model: any = '';
            let team: any = '';
            let nation: any = '';
            let provinceName: any = '';
            let areaName: any = '';
            let manageModelName: any = '';
            let teamName: any = '';
            let nationName: any = '';
            let info=await dTalkApi.getUserDetail(id,access_token);
            //console.log(info,'info_info_info_info_info_')
            if (!info.roles) {
                console.log("---------------未分配角色-------------------------", info);
                return [];
            }
            let roles=info.roles;
            roles.map(it => {
                groupName.push(it.groupName);
            })
            //console.log(groupName,'=======groupName=====')
            //查询指定用户的所有上级父部门路径
            let json_Two = await dTalkApi.list_parent_depts(id,access_token);
            let deptParentList = json_Two.department;
            for (let index = 0; index < json_Two.department.length; index++) {
                let deptParentList = json_Two.department[index];
                if (groupName[0]=='销售'||groupName.includes('销售')) {
                    if(deptParentList.length==3){//B2B
                        province = '';
                        area ='';
                        model = deptParentList[0];
                        nation = deptParentList[1];
                    }else if(deptParentList.length==4) {
                        province = '';
                        area = deptParentList[0];
                        model = deptParentList[1];
                        nation = deptParentList[2];
                    }else if (deptParentList.length==5) {//改动过
                        province = deptParentList[0];
                        area = deptParentList[1];
                        model = deptParentList[2];
                        nation = deptParentList[3];
                    }
                }else if (groupName.includes('省份') ){//---------------------有问题
                   if (deptParentList.length==5) {
                        province = deptParentList[0];
                        area = deptParentList[1];
                        model = deptParentList[2];
                        nation = deptParentList[3];
                    }
                }else if (groupName.includes('区域')) {//改动过
                    if(deptParentList.length==4){//B2B
                        province = '';
                        area = deptParentList[0];
                        model = deptParentList[1];
                        nation = deptParentList[2];
                    }
                }else if (groupName.includes('模块')) {
                    if(deptParentList.length==3){//B2B
                        province = '';
                        area ='';
                        model =  deptParentList[0];
                        nation = deptParentList[1];
                    }
                }else if (groupName.includes('全国')) {
                    if(deptParentList.length==2){
                        province = '';
                        area = '';
                        model = '';
                        nation = deptParentList[0];
                    }
                }
                if (province) {
                    let data1 = await dTalkApi.getDeptDetail(province,access_token);
                    if(data1){
                        provinceName = data1.name;//省份名称
                    }
                }
                if (area) {
                    let data2 = await dTalkApi.getDeptDetail(area,access_token);
                    if(data2){
                        areaName = data2.name;//区域名称
                    }
                }
                if (model) {
                    let data3 = await dTalkApi.getDeptDetail(model,access_token);
                    if(data3){
                        manageModelName = data3.name;//模块名称
                    }       
                }
                if (team) {
                    let data4 = await dTalkApi.getDeptDetail(team,access_token);
                    if(data4){
                        teamName = data4.name;//团队名称
                    }
                }
                if (nation) {
                    let data5 = await dTalkApi.getDeptDetail(nation,access_token);
                    if(data5){
                        nationName = data5.name;//全国名称
                    }
                }
            }
            // console.log('provinceName---------->',provinceName, 'areaName--------->',areaName, 
            // 'manageModelName---------->',manageModelName, ' teamName---------->',teamName, 
            // 'nationName------------->', nationName,'=================员工id:',id,'============')            
            return [provinceName,areaName,manageModelName,teamName,nationName,province,area,model,team,nation,roles]
        }
      
    }

    //保存导入的计划数据
    async saveLeadeData(data: any[]) {
        console.log('保存导入的计划数据开始!!!!!!!!!!!!!!!!!!')
        console.log(data,'data_data_data_data_data_data_')
        let cache: any = {}
        let userIdList:any=[];
        let access_token=await dTalkApiUtil.getAccessToken();
        for (let index = 0; index < data.length; index++) {
            let item = data[index];
            for (let itemindex = 0; itemindex < item.length; itemindex++) {
                let element = item[itemindex];
                //element.employeeName   员工工号
                let provinceName: any = '';
                let areaName: any = '';
                let manageModelName: any = '';
                let teamName: any = '';
                let nationName: any = '';
                let province: any = '';
                let area: any = '';
                let model: any = '';
                let team: any = '';
                let nation: any = '';     
                let planDate2 = moment(element.planDate2).format('YYYY-MM-DD');
                let month = moment(element.planDate2).format('MM');
                let year = moment(element.planDate).format('YYYY');
                if (!(element.employeeName==undefined)) {
                    let result = await this.getUserIdByCode(element.employeeName, cache,access_token)
                    if (!result) {
                        continue;
                    }
                    // console.log("---------------------------------", result, result.staffId);
                    let userId = result.staffId;
                    if(!userIdList.includes(userId)){
                        if(!(element.code == undefined )&& !(element.consumerName == undefined)){
                            userIdList.push(userId);
                        }
                        let s=await this.getUserOriginizationById(userId,cache,access_token);
                        if(s.length==0){
                          continue;
                        }
                        provinceName= s[0];
                        areaName = s[1];
                        manageModelName = s[2];
                        teamName= s[3];
                        nationName = s[4];
                        province =  s[5];
                        area=  s[6];
                        model =  s[7];
                        team =  s[8];
                        nation =  s[9];
                    }
                    let employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    if (!employeeInfo&&!employeeInfo.roles) {
                        console.log("---------------未分配角色-------------------------", employeeInfo);
                        continue;
                    }
                    let department = employeeInfo.department;
                    let userName = employeeInfo.name;
                    if (!(element.code == undefined )&& !(element.consumerName == undefined)) {
                        let type: any = '';
                        if (element.consumerName == '开会') {
                            type = '开会';
                            let a3 = await visitMonthPlanModel.create({
                                sourceId: userId + '&' + element.code,
                                userId: userId,
                                user: userName,
                                avatar: employeeInfo.avatar,
                                jobnumber: element.employeeName,
                                deptId: department,
                                provinceManager: '',
                                areaManager: '',
                                modelManager: "",      //模块负责人
                                nationalManager: "",//全国负责人
                                city: employeeInfo.workPlace,
                                roles: employeeInfo.roles,     //角色
                                province: province,//员工所在省份
                                area: area,//员工所在区域
                                manageModel: model,     //员工所在模块
                                team: team,//员工所在团队
                                nation: nation,
                                provinceName: provinceName,//省份名称
                                areaName: areaName,//区域名称
                                manageModelName: manageModelName,//模块名称
                                teamName: teamName,//团队名称
                                nationName: nationName,//全国名称
                                month: month,
                                visitRecoder: '',
                                channel: '',
                                mark: '',
                                planDate: planDate2,
                                consumerName: element.consumerName,
                                consumerCode: '',
                                consumerAddress:'',
                                isAdjust:false,
                                year:year,
                                rest: '',
                                meeting: '',
                                plantype: type,
                                planStatus: '申请取消',
                                customerType: '',
                                purpose: '',
                                comment: 1,
                                cancelApply: '否',
                                remark: '',
                                leadIndate: moment().format('YYYY-MM-DD')
                            });
                            //    console.log(a3,'a3_a3_a3_a3_a3_a3_a3_a3_a3_a3_a3_')  
                        } else if (element.consumerName == '休假') {
                            type = '休假';
                            let a4 = await visitMonthPlanModel.create( {
                                sourceId: userId + '&' + element.code,
                                userId: userId,
                                user: userName,
                                avatar: employeeInfo.avatar,
                                jobnumber: element.employeeName,
                                deptId: department,
                                provinceManager: '',
                                areaManager: '',
                                modelManager: "",      //模块负责人
                                nationalManager: "",//全国负责人
                                city: employeeInfo.workPlace,
                                roles: employeeInfo.roles,     //角色
                                province: province,//员工所在省份
                                area: area,//员工所在区域
                                manageModel: model,     //员工所在模块
                                team: team,//员工所在团队
                                nation: nation,
                                provinceName: provinceName,//省份名称
                                areaName: areaName,//区域名称
                                manageModelName: manageModelName,//模块名称
                                teamName: teamName,//团队名称
                                nationName: nationName,//全国名称
                                month: month,
                                visitRecoder: '',
                                channel: '',
                                mark: '',
                                planDate: planDate2,
                                consumerName: element.consumerName,
                                consumerCode: '',
                                consumerAddress:'',
                                isAdjust:false,
                                year:year,
                                rest: '',
                                meeting: '',
                                plantype: type,
                                planStatus: '申请取消',
                                customerType: '',
                                purpose: '',
                                comment: 1,
                                cancelApply: '否',
                                remark: '',
                                leadIndate: moment().format('YYYY-MM-DD')
                            });
                            //    console.log(a4,'a4_a4_a4_a4_a4_a4_a4_a4_a4_a4_')  
                        } else {
                            let code1: any = '';
                            if (element.code == undefined) {
                                code1 = '';
                            } else {
                                code1 = element.code;
                            }
                            let customerType:any='';
                            //新增
                            let consumer_address:any='';//<==============新增字段
                            let data1 = await consumerRecoderModel.find({ consumerCode: code1, comment: 1 }, {});
                            let data2 = await storeInfoModel.find({ storeCode: code1 });
                            if (data1.length != 0) {
                                type = '现有客户';
                                customerType=data1[0].typeOne;
                                consumer_address=data1[0].consumerAddress;
                            } else if (data2.length != 0) {
                                type = '门店';
                                customerType=data2[0].store_classification;
                                consumer_address=data2[0].store_address;
                            } else {
                                type = '新拓展客户';
                                customerType='';
                                consumer_address='';
                            }
                            let data = await visitMonthPlanModel.findOne({ planDate: element.planDate2, consumerCode: element.code, consumerName: element.consumerName, jobnumber: element.employeeName });
                            if (data) {
                                console.log("执行修改", data._id )
                                let a_1 = await visitMonthPlanModel.update({ _id: data._id }, {
                                    sourceId: userId + '&' + element.code,
                                    userId: userId,
                                    user: userName,
                                    avatar: employeeInfo.avatar,
                                    jobnumber: element.employeeName,
                                    consumerCode: element.code,
                                    consumerName: element.consumerName,
                                    //=======新增============
                                    consumerAddress:consumer_address,
                                    isAdjust:false,
                                    year:year,
                                    //=======新增============
                                    customerType:customerType,
                                    plantype: type,
                                    planDate: planDate2,
                                    planStatus: '申请取消',
                                    provinceName: provinceName,
                                    areaName: areaName,
                                    manageModelName: manageModelName,
                                    teamName: teamName,
                                    nationName: nationName,
                                    comment: 1,
                                    cancelApply: '否',
                                    leadIndate: moment().format('YYYY-MM-DD')
                                }, { upsert: true });
                            } else {
                                console.log("执行添加")
                                let a2 = await visitMonthPlanModel.create({
                                    sourceId: userId + '&' + element.code,
                                    userId: userId,
                                    user: userName,
                                    avatar: employeeInfo.avatar,
                                    jobnumber: element.employeeName,
                                    deptId: department,
                                    provinceManager: '',
                                    areaManager: '',
                                    modelManager: "",      //模块负责人
                                    nationalManager: "",//全国负责人
                                    city: employeeInfo.workPlace,
                                    roles: employeeInfo.roles,     //角色
                                    province: province,//员工所在省份
                                    area: area,//员工所在区域
                                    manageModel: model,     //员工所在模块
                                    team: team,//员工所在团队
                                    nation: nation,
                                    provinceName: provinceName,//省份名称
                                    areaName: areaName,//区域名称
                                    manageModelName: manageModelName,//模块名称
                                    teamName: teamName,//团队名称
                                    nationName: nationName,//全国名称
                                    month: month,
                                    visitRecoder: '',
                                    channel: '',
                                    mark: '',
                                    planDate: planDate2,
                                    consumerName: element.consumerName,
                                    consumerCode: element.code,
                                    //=======新增============
                                    consumerAddress:consumer_address,//客户地址
                                    isAdjust:false,
                                    year:year,
                                    //=======新增============
                                    rest: '',
                                    meeting: '',
                                    plantype: type,
                                    planStatus: '申请取消',
                                    customerType:customerType,
                                    purpose: '',
                                    comment: 1,
                                    cancelApply: '否',
                                    remark: '',
                                    leadIndate: moment().format('YYYY-MM-DD')
                                });
                                console.log(a2,'a2_a2_a2_a2_a2_a2_a2_a2_')
                            }
                        }
                    } 
                }
            }
        } 
        console.log('保存导入的计划数据结束!!!!!!!!!!!!!!!!!!11')
    }

    //逐条显示一个员工的月拜访计划
    //userId:员工id month:月份
    async listMonthPlan2(userId: string, month: string) {
        console.log('员工id:' + userId + ',月份是:' + month);
        let json: any = {};//一个员工一个月的计划
        let dataCache:any=[]
        let json_monthPlan_day: any = [];
        //let year=moment().format('YYYY');//当年的年份
        //let data=await visitMonthPlanModel.find({userId:userId,month:month,year:year}).sort({planDate:1});
        let data=await visitMonthPlanModel.find({userId:userId,month:month}).sort({planDate:1});
        for (let index = 0; index < data.length; index++) {
            let element = data[index];
            if(!dataCache[element.planDate]){
                dataCache[element.planDate]={
                   planDate:element.planDate,
                   data:[]
                }
            }
            let recoderDetail: any = '';
            if (!element.visitRecoder) {
                recoderDetail = '';
            } else {
                if (element.plantype == '门店') {
                    recoderDetail = await storeRecoderModel.findById({ _id: element.visitRecoder });
                } else {
                    recoderDetail = await consumerRecoderModel.findById({ _id: element.visitRecoder });
                }
            }
            // console.log(element,'ele_ele_ele_ele_ele_ele_ele_ele_')
            let status:any='';
            if(element.comment !=1){
               status=element.planStatus
            }
            dataCache[element.planDate].data.push({
                id: element._id,//隐藏  mongodb数据库自建的_id
                plantype: element.plantype,
                customerType: element.customerType,//客户类型
                consumerName: element.consumerName,//客户名称
                consumerCode: element.consumerCode,//客户编码
                planDate: element.planDate,//拜访日期
                planStatus: status,  //计划的状态
                purpose: element.purpose,//拜访目的
                comment: element.comment,
                visitRecoder: recoderDetail
            });
        }
      
        for (const key in dataCache) {
            if (dataCache.hasOwnProperty(key)) {
                let element = dataCache[key];
                json_monthPlan_day.push(element)
            }
        }
        //(二)Header部分:统计数据部分
        //一个员工一月计划拜访的条数
        let toalcount_month = await visitMonthPlanModel.count({ userId: userId, month: month, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' },{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}] });
        //一个月已拜访门店的总数量
        let countStore = await storeRecoderModel.count({ userid: userId, month: month, planType: '门店' });
        // 一个月已拜访门店的门店达标的总数量 
        let reachStandard_store_count = await storeRecoderModel.count({ userid: userId, month: month, planType: '门店', isListStandard: true });
        let countConsumer = await consumerRecoderModel.count({ userid: userId, month: month, comment: 2 });
        
        // let toalcount_month = await visitMonthPlanModel.collection.countDocuments({ userId: userId, month: month,year:year, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' },{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}] });
        // let countStore = await storeRecoderModel.collection.countDocuments({ userid: userId, month: month,year:year, planType: '门店' });
        // let reachStandard_store_count = await storeRecoderModel.collection.countDocuments({ userid: userId, month: month,year:year, planType: '门店', isListStandard: true });
        // let countConsumer = await consumerRecoderModel.collection.countDocuments({ userid: userId, month: month,year:year, comment: 2 });
        
        let totalcount_month_visited = countStore + countConsumer;
        //门店达标率
        let storeRate_ = 0;
        if (countStore == 0) {
            storeRate_ = 0;
        } else {
            storeRate_ = (reachStandard_store_count / countStore) * 100;
        }
        let storeRate = storeRate_.toFixed(2);
        let consumerRate_ = 0;
        if (toalcount_month == 0) {
            consumerRate_ = 0;
        } else {
            consumerRate_ = (totalcount_month_visited / toalcount_month) * 100;
        }
        let consumerRate = consumerRate_.toFixed(2);
        json = {
            header: {
                one: '计划' + toalcount_month + '家,|达成' + totalcount_month_visited + '家',
                two: '客户拜访达成率' + consumerRate + '%',
                three: '已拜访门店' + countStore,
                four: '门店达标率' + storeRate + '%'
            },
            json_body: json_monthPlan_day
        }
        return json;
    }



}
let visitMonthPlan = new VisitMonthPlanService();
export default visitMonthPlan;